package org.kjtc.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.kjtc.entity.ChargingRecord;
import org.kjtc.entity.ChargingStation;
import org.kjtc.entity.ChargingStationStatus;
import org.kjtc.entity.DeviceObject;
import org.kjtc.service.ChargingRecordService;
import org.kjtc.service.ChargingStationService;
import org.kjtc.util.Const;
import org.kjtc.util.RequestUtil;
import org.kjtc.util.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ChargingStationRequestController extends BaseController {

	@Resource(name = "deviceObject")
    private DeviceObject deviceObject;

	@Resource(name = "chargingStationService")
	private ChargingStationService chargingStationService;

	@Resource(name = "chargingRecordService")
	private ChargingRecordService chargingRecordService;

	@ResponseBody
	@RequestMapping(value = "/subStation/request")
	public Object getSubStationRequest(HttpServletRequest request, @RequestBody String requestBody) {

		Map<String, Object> map = new HashMap<String, Object>();
		Date requestDTTM = new Date();
		try {
			logger.info("充电站访问信息：【IP：" + Tools.getIPAddress(request) + ", 主机名" + request.getRemoteHost() + ", 端口" + request.getRemotePort() + "】");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
//		logger.info("子站解密前请求实时状态数据：" + requestBody);
		JSONObject json = JSONObject.fromObject(requestBody);
		JSONObject realTimeJson = Tools.getJsonData(json, "realTimeData", Tools.date2Str(requestDTTM, "yyyy-MM-dd HH:mm:ss"));
		logger.info("子站请求数据realTimeData:");
		if (realTimeJson != null) {
			String chargingStationID = null;
			// 充电站实时数据
			if (realTimeJson.has("chargingStationID")) {
				chargingStationID = realTimeJson.getString("chargingStationID");
				if (chargingStationID != null && !chargingStationID.isEmpty()) {
					// 充电桩数据
					JSONArray jsonArray = null;
					int chargingCount = 0;
					int chargedCount = 0;
					int idleCount = 0;
					int offLineCount = 0;
					int faultCount = 0;
					if (realTimeJson.has("equipmentData")) {
						jsonArray = realTimeJson.getJSONArray("equipmentData");
						int length = jsonArray.size();
						JSONObject equipmentJson = null;
						for (int i = 0; i < length; i++) {
							equipmentJson = jsonArray.getJSONObject(i);
							if (equipmentJson != null) {
								Map<String, Object> operateDeviceMap = deviceObject.getOperateDeviceMap();
								if (operateDeviceMap != null && operateDeviceMap.get(realTimeJson.getString("chargingStationID") + equipmentJson.getString("equipmentID")) != null) {
									map.put("chargingRequestInfo", operateDeviceMap.get(realTimeJson.getString("chargingStationID") + equipmentJson.getString("equipmentID")));
								}
								if (equipmentJson.has("communicationState")){
									if (equipmentJson.getString("communicationState").equals(Const.EQUIPMENT_OFFLINE)) {
										offLineCount++;
									} else if (equipmentJson.getString("communicationState").equals(Const.EQUIPMENT_ONLINE)) {
										if (equipmentJson.has("deviceState")) {
											if (equipmentJson.getString("deviceState").equals(Const.EQUIPMENT_CHARGING)) {
												chargingCount++;
											} else if (equipmentJson.getString("deviceState").equals(Const.EQUIPMENT_CHARGED)) {
												chargedCount++;
											} else if (equipmentJson.getString("deviceState").equals(Const.EQUIPMENT_IDLE)) {
												idleCount++;
											} else if (equipmentJson.getString("deviceState").equals(Const.EQUIPMENT_FAULT)) {
												faultCount++;
											}
										}
									}
								}
							}
							equipmentJson = null;
						}
					} else {
						logger.error("子站请求实时状态数据没有'equipmentData'，无法接收桩的数据");
					}

					ChargingStationStatus chargingStationStatus = null;
					Map<String, Object> subStationMap = deviceObject.getSubStationMap();
					String chargingStationIDList = deviceObject.getChargingStationIDList();
					if (subStationMap == null) {
						subStationMap = new HashMap<String, Object>();
					}
					if (subStationMap.containsKey(chargingStationID)){

					} else {
						if (chargingStationIDList == null || chargingStationIDList.isEmpty()) {
							chargingStationIDList = chargingStationID;
						} else {
							chargingStationIDList = chargingStationIDList + "," + chargingStationID;
						}
						deviceObject.setChargingStationIDList(chargingStationIDList);
						chargingStationStatus = new ChargingStationStatus();
						chargingStationStatus.setChargingStationID(chargingStationID);
					}
					if (realTimeJson.has("currentVersion")) {
						chargingStationStatus.setCurrentVersion(realTimeJson.getString("currentVersion"));
					} else {
						logger.info("子站" + chargingStationID + "请求实时状态数据没有项目'currentVersion'，无法获取版本信息");
					}
					chargingStationStatus.setEquipmentChargingCount(chargingCount);
					chargingStationStatus.setEquipmentChargedCount(chargedCount);
					chargingStationStatus.setEquipmentIdleCount(idleCount);
					chargingStationStatus.setEquipmentOfflineCount(offLineCount);
					chargingStationStatus.setEquipmentFaultCount(faultCount);
					chargingStationStatus.setOffLineCount(offLineCount);
					chargingStationStatus.setOnLineCount(chargingCount + chargedCount + idleCount + faultCount);
					chargingStationStatus.setRequestDTTM(requestDTTM);
					chargingStationStatus.setEquipmentData(jsonArray);
					chargingStationStatus.setOnlineStatus(true);
//					requestDTTM = null;
					subStationMap.put(chargingStationID, chargingStationStatus);
					deviceObject.setSubStationMap(subStationMap);
				} else {
					logger.error("子站请求实时状态数据中'chargingStationID'为空，无法接收站的数据");
				}
			} else {
				logger.error("子站请求实时状态数据没有项目'chargingStationID'，无法接收站的数据");
			}
		} else {
			logger.error("子站请求实时状态数据为空");
		}

		map.put("result", "Success");
		String jsonResult = JSONObject.fromObject(map).toString();
		logger.info("云平台接收子站实时状态返回数据：" + jsonResult);
		map = null;
		return jsonResult;
	}
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "/subStation/uploadChargingRecord")
	public Object uploadChargingRecord(HttpServletRequest request, @RequestBody String requestBody) {

		Map<String, Object> map = new HashMap<String, Object>();
		Date requestDTTM = new Date();
		JSONObject json = JSONObject.fromObject(requestBody);
		logger.info("子站上传充电记录数据chargingRecordData：");
		JSONArray chargingRecordJsonArray = Tools.getJsonArrayData(json, "chargingRecordData");

		if (chargingRecordJsonArray != null) {
			Iterator itArray = chargingRecordJsonArray.iterator();
			Map<String, String> jsonMap = new HashMap<String, String>();
			List<ChargingRecord> chargingRecordList = new ArrayList<ChargingRecord>();
			List<ChargingRecord> abnormalChargingRecordList = new ArrayList<ChargingRecord>();
			while (itArray.hasNext()){
				JSONObject chargingRecordJsonObject = (JSONObject) itArray.next();
				Iterator it = chargingRecordJsonObject.keys();
				while (it.hasNext()){
					String key = String.valueOf(it.next());
					String value = chargingRecordJsonObject.getString(key);
					jsonMap.put(key, value);
				}
				ChargingRecord chargingRecord = new ChargingRecord();
				if (jsonMap.get("equipmentID") != null && !"null".equals(jsonMap.get("equipmentID"))) {
					chargingRecord.setEquipmentNo(jsonMap.get("equipmentID"));
				}
				if (jsonMap.get("equipmentName") != null && !"null".equals(jsonMap.get("equipmentName"))) {
					chargingRecord.setEquipmentName(jsonMap.get("equipmentName"));
				}
				if (jsonMap.get("chargingStationID") != null && !"null".equals(jsonMap.get("chargingStationID"))) {
					chargingRecord.setChargingStationID(jsonMap.get("chargingStationID"));
				}
				if (jsonMap.get("chargingStationName") != null && !"null".equals(jsonMap.get("chargingStationName"))) {
					chargingRecord.setChargingStationName(jsonMap.get("chargingStationName"));
				}
				if (jsonMap.get("cardNo") != null && !"null".equals(jsonMap.get("cardNo"))) {
					chargingRecord.setCardNo(jsonMap.get("cardNo"));
				}
				if (jsonMap.get("carNo") != null && !"null".equals(jsonMap.get("carNo"))) {
					chargingRecord.setCarNo(jsonMap.get("carNo"));
				}
				if (jsonMap.get("carNumber") != null && !"null".equals(jsonMap.get("carNumber"))) {
					chargingRecord.setCarNumber(jsonMap.get("carNumber"));
				}
				if (jsonMap.get("lineName") != null && !"null".equals(jsonMap.get("lineName"))) {
					chargingRecord.setLineID(jsonMap.get("lineName"));
				}
				if (jsonMap.get("branchCompany") != null && !"null".equals(jsonMap.get("branchCompany"))) {
					chargingRecord.setSubBranchCompanyID(jsonMap.get("branchCompany"));
				}
				if (jsonMap.get("startChargingDTTM") != null && !"null".equals(jsonMap.get("startChargingDTTM"))) {
					chargingRecord.setStartChargingDTTM(Tools.str2DateTime(jsonMap.get("startChargingDTTM")));
				}
				if (jsonMap.get("endChargingDTTM") != null && !"null".equals(jsonMap.get("endChargingDTTM"))) {
					chargingRecord.setEndChargingDTTM(Tools.str2DateTime(jsonMap.get("endChargingDTTM")));
				}
				if (jsonMap.get("startSOC") != null && !"null".equals(jsonMap.get("startSOC"))) {
					chargingRecord.setStartSOC(Double.parseDouble(jsonMap.get("startSOC")));
				}
				if (jsonMap.get("endSOC") != null && !"null".equals(jsonMap.get("endSOC"))) {
					chargingRecord.setEndSOC(Double.parseDouble(jsonMap.get("endSOC")));
				}
				if (jsonMap.get("startVoltage") != null && !"null".equals(jsonMap.get("startVoltage"))) {
					chargingRecord.setMinTotalVoltage(Double.parseDouble(jsonMap.get("startVoltage")));
				}
				if (jsonMap.get("endVoltage") != null && !"null".equals(jsonMap.get("endVoltage"))) {
					chargingRecord.setMaxTotalVoltage(Double.parseDouble(jsonMap.get("endVoltage")));
				}
				if (jsonMap.get("maxCurrent") != null && !"null".equals(jsonMap.get("maxCurrent"))) {
					chargingRecord.setMaxTotalCurrent(Double.parseDouble(jsonMap.get("maxCurrent")));
				}
				if (jsonMap.get("aveCurrent") != null && !"null".equals(jsonMap.get("aveCurrent"))) {
					chargingRecord.setAveCurrent(Double.parseDouble(jsonMap.get("aveCurrent")));
				}
				if (jsonMap.get("startAmmeterNo") != null && !"null".equals(jsonMap.get("startAmmeterNo"))) {
					chargingRecord.setStartAmmeterNo(Double.parseDouble(jsonMap.get("startAmmeterNo")));
				}
				if (jsonMap.get("endAmmeterNo") != null && !"null".equals(jsonMap.get("endAmmeterNo"))) {
					chargingRecord.setEndAmmeterNo(Double.parseDouble(jsonMap.get("endAmmeterNo")));
				}
				if (jsonMap.get("totalSOC") != null && !"null".equals(jsonMap.get("totalSOC"))) {
					chargingRecord.setTotalSOC(Double.parseDouble(jsonMap.get("totalSOC")));
				}
				if (jsonMap.get("totalChargingKWH") != null && !"null".equals(jsonMap.get("totalChargingKWH"))) {
					chargingRecord.setTotalChargingKWH(Double.parseDouble(jsonMap.get("totalChargingKWH")));
				}
				if (jsonMap.get("totalChargingDTTM") != null && !"null".equals(jsonMap.get("totalChargingDTTM"))) {
					chargingRecord.setTotalChargingDTTM(Long.parseLong(jsonMap.get("totalChargingDTTM")));
				}
				if (jsonMap.get("endReason") != null && !"null".equals(jsonMap.get("endReason"))) {
					chargingRecord.setEndReason(jsonMap.get("endReason"));
				}
				if (jsonMap.get("carFile") != null && !"null".equals(jsonMap.get("carFile"))) {
					chargingRecord.setCarFile(jsonMap.get("carFile"));
				}
				if (jsonMap.get("abnormalFlag") != null && !"null".equals(jsonMap.get("abnormalFlag"))) {
					chargingRecord.setAbnormalFlag(jsonMap.get("abnormalFlag"));
				}
				if (jsonMap.get("abnormalReason") != null && !"null".equals(jsonMap.get("abnormalReason"))) {
					chargingRecord.setAbnormalReason(jsonMap.get("abnormalReason"));
				}
				if (jsonMap.get("resendFlag") != null && !"null".equals(jsonMap.get("resendFlag"))) {
					chargingRecord.setResendFlag(jsonMap.get("resendFlag"));
				}
				if (jsonMap.get("createDTTM") != null && !"null".equals(jsonMap.get("createDTTM"))) {
					chargingRecord.setStationCreateDTTM(Tools.str2DateTime(jsonMap.get("createDTTM")));
				}
				if (jsonMap.get("updateDTTM") != null && !"null".equals(jsonMap.get("updateDTTM"))) {
					chargingRecord.setStationUpdateDTTM(Tools.str2DateTime(jsonMap.get("updateDTTM")));
				}
				if (jsonMap.get("message") != null && !"null".equals(jsonMap.get("message"))) {
					chargingRecord.setMessage(jsonMap.get("message"));
				}
				if (jsonMap.get("chargedAmount") != null && !"null".equals(jsonMap.get("chargedAmount"))) {
					chargingRecord.setTotalChargingAmount(Double.parseDouble(jsonMap.get("chargedAmount")));
				}
				if (jsonMap.get("discountAmount") != null && !"null".equals(jsonMap.get("discountAmount"))) {
					chargingRecord.setDiscountAmount(Double.parseDouble(jsonMap.get("discountAmount")));
				}
				if (jsonMap.get("sharpStartChargingDTTM") != null && !jsonMap.get("sharpStartChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("sharpStartChargingDTTM"))) {
					chargingRecord.setSharpStartChargingDTTM(Tools.str2DateTime(jsonMap.get("sharpStartChargingDTTM")));
				}
				if (jsonMap.get("sharpEndChargingDTTM") != null && !jsonMap.get("sharpEndChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("sharpEndChargingDTTM"))) {
					chargingRecord.setSharpEndChargingDTTM(Tools.str2DateTime(jsonMap.get("sharpEndChargingDTTM")));
				}
				if (jsonMap.get("sharpTotalChargingDTTM") != null && !jsonMap.get("sharpTotalChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("sharpTotalChargingDTTM"))) {
					chargingRecord.setSharpTotalChargingDTTM(Long.parseLong(jsonMap.get("sharpTotalChargingDTTM")));
				}
				if (jsonMap.get("sharpTotalChargingKWH") != null && !jsonMap.get("sharpTotalChargingKWH").isEmpty() && !"null".equals(jsonMap.get("sharpTotalChargingKWH"))) {
					chargingRecord.setSharpTotalChargingKWH(Double.parseDouble(jsonMap.get("sharpTotalChargingKWH")));
				}
				if (jsonMap.get("sharpTotalChargingAmount") != null && !jsonMap.get("sharpTotalChargingAmount").isEmpty() && !"null".equals(jsonMap.get("sharpTotalChargingAmount"))) {
					chargingRecord.setSharpTotalChargingAmount(Double.parseDouble(jsonMap.get("sharpTotalChargingAmount")));
				}
				if (jsonMap.get("peakStartChargingDTTM") != null && !jsonMap.get("peakStartChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("peakStartChargingDTTM"))) {
					chargingRecord.setPeakStartChargingDTTM(Tools.str2DateTime(jsonMap.get("peakStartChargingDTTM")));
				}
				if (jsonMap.get("peakEndChargingDTTM") != null && !jsonMap.get("peakEndChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("peakEndChargingDTTM"))) {
					chargingRecord.setPeakEndChargingDTTM(Tools.str2DateTime(jsonMap.get("peakEndChargingDTTM")));
				}
				if (jsonMap.get("peakTotalChargingDTTM") != null && !jsonMap.get("peakTotalChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("peakTotalChargingDTTM"))) {
					chargingRecord.setPeakTotalChargingDTTM(Long.parseLong(jsonMap.get("peakTotalChargingDTTM")));
				}
				if (jsonMap.get("peakTotalChargingKWH") != null && !jsonMap.get("peakTotalChargingKWH").isEmpty() && !"null".equals(jsonMap.get("peakTotalChargingKWH"))) {
					chargingRecord.setPeakTotalChargingKWH(Double.parseDouble(jsonMap.get("peakTotalChargingKWH")));
				}
				if (jsonMap.get("peakTotalChargingAmount") != null && !jsonMap.get("peakTotalChargingAmount").isEmpty() && !"null".equals(jsonMap.get("peakTotalChargingAmount"))) {
					chargingRecord.setPeakTotalChargingAmount(Double.parseDouble(jsonMap.get("peakTotalChargingAmount")));
				}
				if (jsonMap.get("flatStartChargingDTTM") != null && !jsonMap.get("flatStartChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("flatStartChargingDTTM"))) {
					chargingRecord.setFlatStartChargingDTTM(Tools.str2DateTime(jsonMap.get("flatStartChargingDTTM")));
				}
				if (jsonMap.get("flatEndChargingDTTM") != null && !jsonMap.get("flatEndChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("flatEndChargingDTTM"))) {
					chargingRecord.setFlatEndChargingDTTM(Tools.str2DateTime(jsonMap.get("flatEndChargingDTTM")));
				}
				if (jsonMap.get("flatTotalChargingDTTM") != null && !jsonMap.get("flatTotalChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("flatTotalChargingDTTM"))) {
					chargingRecord.setFlatTotalChargingDTTM(Long.parseLong(jsonMap.get("flatTotalChargingDTTM")));
				}
				if (jsonMap.get("flatTotalChargingKWH") != null && !jsonMap.get("flatTotalChargingKWH").isEmpty() && !"null".equals(jsonMap.get("flatTotalChargingKWH"))) {
					chargingRecord.setFlatTotalChargingKWH(Double.parseDouble(jsonMap.get("flatTotalChargingKWH")));
				}
				if (jsonMap.get("flatTotalChargingAmount") != null && !jsonMap.get("flatTotalChargingAmount").isEmpty() && !"null".equals(jsonMap.get("flatTotalChargingAmount"))) {
					chargingRecord.setFlatTotalChargingAmount(Double.parseDouble(jsonMap.get("flatTotalChargingAmount")));
				}
				if (jsonMap.get("valleyStartChargingDTTM") != null && !jsonMap.get("valleyStartChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("valleyStartChargingDTTM"))) {
					chargingRecord.setValleyStartChargingDTTM(Tools.str2DateTime(jsonMap.get("valleyStartChargingDTTM")));
				}
				if (jsonMap.get("valleyEndChargingDTTM") != null && !jsonMap.get("valleyEndChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("valleyEndChargingDTTM"))) {
					chargingRecord.setValleyEndChargingDTTM(Tools.str2DateTime(jsonMap.get("valleyEndChargingDTTM")));
				}
				if (jsonMap.get("valleyTotalChargingDTTM") != null && !jsonMap.get("valleyTotalChargingDTTM").isEmpty() && !"null".equals(jsonMap.get("valleyTotalChargingDTTM"))) {
					chargingRecord.setValleyTotalChargingDTTM(Long.parseLong(jsonMap.get("valleyTotalChargingDTTM")));
				}
				if (jsonMap.get("valleyTotalChargingKWH") != null && !jsonMap.get("valleyTotalChargingKWH").isEmpty() && !"null".equals(jsonMap.get("valleyTotalChargingKWH"))) {
					chargingRecord.setValleyTotalChargingKWH(Double.parseDouble(jsonMap.get("valleyTotalChargingKWH")));
				}
				if (jsonMap.get("valleyTotalChargingAmount") != null && !jsonMap.get("valleyTotalChargingAmount").isEmpty() && !"null".equals(jsonMap.get("valleyTotalChargingAmount"))) {
					chargingRecord.setValleyTotalChargingAmount(Double.parseDouble(jsonMap.get("valleyTotalChargingAmount")));
				}
				chargingRecord.setCreateDTTM(requestDTTM);
				chargingRecord.setUpdateDTTM(requestDTTM);

				if ("1".equals(chargingRecord.getAbnormalFlag())) {
					abnormalChargingRecordList.add(chargingRecord);
				} else {
					chargingRecordList.add(chargingRecord);
				}
			}
			try {
				int length = chargingRecordList.size();
				int count = 0;
				if (length > 0) {
					count = chargingRecordService.saveChargingRecord(chargingRecordList, "remote", "0");
					logger.info("保存充电站正常充电记录" + count + "条");
					if (length - count > 0) {
						logger.info("忽略充电站重复正常充电记录" + (length - count) + "条");
					}
				}

				length = abnormalChargingRecordList.size();
				if (length > 0) {
					count = chargingRecordService.saveAbnormalChargingRecord(abnormalChargingRecordList, "remote", "0");
					logger.info("保存充电站异常充电记录" + count + "条");
					if (length - count > 0) {
						logger.info("忽略充电站重复异常充电记录" + (length - count) + "条");
					}
				}

				map.put("result", "Success");

				if (jsonMap.get("chargingStationID") != null && !"null".equals(jsonMap.get("chargingStationID"))) {
					ChargingStation chargingStation = new ChargingStation();
					chargingStation.setChargingStationID(jsonMap.get("chargingStationID"));
					chargingStation = chargingStationService.getChargingStationPay(chargingStation);
					if (chargingStation.isPay()) {
						getChargingPay(map, jsonMap);
					}
					chargingStation = null;
				}
			} catch (Exception e) {
				map.put("result", "Failed");
				e.printStackTrace();
				logger.error("保存充电站充电记录异常：" + e.getMessage());
			}
			chargingRecordList = null;
			abnormalChargingRecordList = null;
			jsonMap = null;
		} else {
			logger.error("子站上传充电记录数据不存在！");
			map.put("result", "NotFound");
		}

		String jsonResult = JSONObject.fromObject(map).toString();
		logger.info("云平台接收充电站充电记录返回数据：" + jsonResult);
		map = null;
		return jsonResult;
	}

	@ResponseBody
	@RequestMapping(value = "/subStation/uploadFile")
	public Object getSubStationFile(HttpServletRequest request,
			@RequestParam(value="chargingStationID", required=false) String chargingStationID,
			@RequestParam(value="type", required=false) String type) {

		Map<String, Object> map = new HashMap<String, Object>();
		Date start = new Date();
		String filePath = null;
		String fileName = request.getHeader("FileName");
		String fileDateTime = request.getHeader("FileDateTime");
		String DateType = request.getHeader("DateType");
		logger.info("充电站" + chargingStationID + "上传文件" + fileName + "开始时间：" + start);
	    try {
	    	if (chargingStationID != null && !chargingStationID.isEmpty()) {
	    		if (type != null && !type.isEmpty()) {
	    			if ("CHARGINGPROCESS".equals(type.toUpperCase())) {
	    				filePath = Const.CHARGINGPROCESS_PATH;
	    				if ("CAR".equals(type.toUpperCase())) {
	    					filePath = filePath + "car" + File.separator;
	    				} else if ("EQUIPMENT".equals(type.toUpperCase())) {
	    					filePath = filePath + "equipment" + File.separator;
	    				}
	    			} else {
	    				filePath = Const.CONFIG_PATH + type + File.separator;
	    			}
	    		} else {
	    			logger.warn("文件类型type为空！");
	    			filePath = Const.CHARGINGPROCESS_PATH;
	    		}
	    		if (fileDateTime != null && !fileDateTime.isEmpty()) {
		    		if (!Tools.isNumeric(fileDateTime)) {
		    			logger.error("充电站" + chargingStationID + "上传文件" + fileName + "时间必须是数字：'" + fileDateTime);
		    		} else {
		    			int fileLength = fileDateTime.length();
		    			if (fileLength >= 8) {
		    				if (DateType == null || DateType.isEmpty() || "DAY".equals(DateType.toUpperCase())) {
			    				filePath = filePath + fileDateTime.substring(0, 4) + File.separator +
			    						fileDateTime.substring(4, 6) + File.separator +
										fileDateTime.substring(6, 8) + File.separator;
			    			} else if ("MONTH".equals(DateType.toUpperCase())) {
			    				filePath = filePath + fileDateTime.substring(0, 4) + File.separator +
			    						fileDateTime.substring(4, 6) + File.separator;
			    			} else if ("YEAR".equals(DateType.toUpperCase())) {
			    				filePath = filePath + fileDateTime.substring(0, 4) + File.separator;
			    			}
		    			} else {
		    				logger.error("充电站" + chargingStationID + "上传文件" + fileName + "时间至少是8位数字：'" + fileDateTime);
		    			}
		    		}
		    	} else {
		    		int fileLength = fileName.length();
					if (fileLength > 18) {
						if (!Tools.isNumeric(fileName.substring(fileLength - 18, fileLength - 4))) {
							map.put("result", "Failed");
							logger.error("充电站" + chargingStationID + "上传充电过程文件" + fileName + "失败，充电过程文件名称错误，必须是'车自编号或桩号+开始充电时间：'" + fileName);
						} else {
							filePath = filePath + chargingStationID + File.separator +
									fileName.substring(0, fileLength - 18).replaceAll(",", "") + File.separator +
									fileName.substring(fileLength - 18, fileLength - 14) + File.separator +
									fileName.substring(fileLength - 14, fileLength - 12) + File.separator +
									fileName.substring(fileLength - 12, fileLength - 10) + File.separator + fileName;
						}
					} else {
						map.put("result", "Failed");
						logger.error("充电站" + chargingStationID + "上传充电过程文件" + fileName + "失败，充电过程文件名称错误，长度不能小于18：" + fileName);
					}
		    	}

				File file = new File(filePath);
			    if (!file.exists()) {
			    	InputStream iputstream = request.getInputStream();
			    	byte[] buffer = new byte[4*1024];
			    	int len = 0;
				    while((len = iputstream.read(buffer)) != -1){
				    	FileUtils.writeByteArrayToFile(file, buffer, 0, len, true);
				    }
				    buffer = null;
				    iputstream.close();
		 		    iputstream = null;
		 		    map.put("result", "Success");
		 		    logger.info("充电站" + chargingStationID + "上传充电过程文件" + fileName + "成功:" + filePath);
			    } else {
			    	map.put("result", "Success");
			    	logger.error("充电站" + chargingStationID + "上传充电过程文件" + fileName + "失败，充电过程文件已存在:" + filePath);
			    }
			    Date end = new Date();
	    		logger.info("充电站" + chargingStationID + "上传文件" + fileName + "结束时间：" + end);
	    	} else {
	    		map.put("result", "Error");
	    		logger.error("充电站ID不存在！");
	    	}

		} catch (IOException e) {
			map.put("result", "SendFailed");
			e.printStackTrace();
			logger.error("充电站" + chargingStationID + "上传文件" + fileName + "异常：" + e.getMessage());
		}

		String jsonResult = JSONObject.fromObject(map).toString();
		logger.info("云平台接收充电站上传文件后返回数据：" + jsonResult);

		return jsonResult;
	}
	public void getChargingPay(Map<String, Object> map, Map<String, String> jsonMap) {
		Map<String, Object> chargingMap = new HashMap<String, Object>();
		chargingMap.put("orderNumber", jsonMap.get("orderNumber"));
		chargingMap.put("equipmentID", jsonMap.get("equipmentID"));
		chargingMap.put("equipmentName", jsonMap.get("equipmentName"));
		chargingMap.put("chargingStationID", jsonMap.get("chargingStationID"));
		chargingMap.put("chargingStationName", jsonMap.get("chargingStationName"));
		chargingMap.put("totalChargingKWH", jsonMap.get("totalChargingKWH"));
		chargingMap.put("totalChargingDTTM", jsonMap.get("totalChargingDTTM"));
		chargingMap.put("chargedAmount", jsonMap.get("chargedAmount"));
		chargingMap.put("sharpStartChargingDTTM", jsonMap.get("sharpStartChargingDTTM"));
		chargingMap.put("sharpEndChargingDTTM", jsonMap.get("sharpEndChargingDTTM"));
		chargingMap.put("sharpTotalChargingDTTM", jsonMap.get("sharpTotalChargingDTTM"));
		chargingMap.put("sharpTotalChargingKWH", jsonMap.get("sharpTotalChargingKWH"));
		chargingMap.put("sharpTotalChargingAmount", jsonMap.get("sharpTotalChargingAmount"));
		chargingMap.put("peakStartChargingDTTM", jsonMap.get("peakStartChargingDTTM"));
		chargingMap.put("peakEndChargingDTTM", jsonMap.get("peakEndChargingDTTM"));
		chargingMap.put("peakTotalChargingDTTM", jsonMap.get("peakTotalChargingDTTM"));
		chargingMap.put("peakTotalChargingKWH", jsonMap.get("peakTotalChargingKWH"));
		chargingMap.put("peakTotalChargingAmount", jsonMap.get("peakTotalChargingAmount"));
		chargingMap.put("flatStartChargingDTTM", jsonMap.get("flatStartChargingDTTM"));
		chargingMap.put("flatEndChargingDTTM", jsonMap.get("flatEndChargingDTTM"));
		chargingMap.put("flatTotalChargingDTTM", jsonMap.get("flatTotalChargingDTTM"));
		chargingMap.put("flatTotalChargingKWH", jsonMap.get("flatTotalChargingKWH"));
		chargingMap.put("flatTotalChargingAmount", jsonMap.get("flatTotalChargingAmount"));
		chargingMap.put("valleyStartChargingDTTM", jsonMap.get("valleyStartChargingDTTM"));
		chargingMap.put("valleyEndChargingDTTM", jsonMap.get("valleyEndChargingDTTM"));
		chargingMap.put("valleyTotalChargingDTTM", jsonMap.get("valleyTotalChargingDTTM"));
		chargingMap.put("valleyTotalChargingKWH", jsonMap.get("valleyTotalChargingKWH"));
		chargingMap.put("valleyTotalChargingAmount", jsonMap.get("valleyTotalChargingAmount"));
		chargingMap.put("discountAmount", jsonMap.get("discountAmount"));
		Map<String, Object> chargingTokenMap = deviceObject.getChargingTokenMap();
		if (chargingTokenMap != null) {
			chargingMap.put("token", chargingTokenMap.get(jsonMap.get("equipmentID")));
		}
		try {
			chargingServiceRequest(map, chargingMap, 3);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("平台请求计费云服务异常：" + e.getMessage());
			map.put("resultPay", "Error");
		}
	}

	private void chargingServiceRequest(Map<String, Object> map, Map<String, Object> chargingMap, int count) throws Exception {
		if (count == 0) {
			logger.error("请求充电计费服务器失败，请求超时或者请求异常");
			map.put("resultPay", "Error");
		} else {
			JSONObject chargingResponeJson = RequestUtil.requestHttpUrl(Const.CHARGING_TOPAY, chargingMap);
			if (chargingResponeJson == null && count > 0) {
				count = count - 1;
				chargingServiceRequest(map, chargingMap, count);
			} else {
				if (chargingResponeJson.containsKey("chargingRecordData")) {
					map.put("chargingRecordData", chargingResponeJson.get("chargingRecordData"));
					map.put("resultPay", "Success");
				} else {
					logger.error("充电计费服务器返回数据异常，'chargingRecordData'不存在！");
					map.put("resultPay", "Error");
				}
			}
		}
	}
}